package it.alb.calcolatrice;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.TextView;

import com.example.calcolatrice.R;

public class Utility extends Activity{
	
	private static SharedPreferences settings;
	
	public static void setTheme(View mainActivity, View resultBox, Context ctx){
        
		TextView risultato = (TextView) resultBox;
		settings = PreferenceManager.getDefaultSharedPreferences(ctx);
        int coloreSfondo=0;
        String colore = settings.getString("bkg_color", "#000000");
	        if (colore.contains("#")){
	        	coloreSfondo = Color.parseColor(colore);
	        	mainActivity.setBackgroundColor(coloreSfondo);
	        }else{
	        	mainActivity.setBackgroundResource(R.drawable.astratto);
	        }
        
	        if (coloreSfondo == Color.parseColor("#000000")){
	        	risultato.setTextColor(Color.parseColor("#FFFFFF"));
	        	risultato.setShadowLayer(15, 2, 5, Color.parseColor("#FFFFFF"));
	        }else{
	        	risultato.setTextColor(Color.parseColor("#000000"));
	        	risultato.setShadowLayer(15, 2, 5, Color.parseColor("#000000"));
	        }
        	
    }
	
	public static void calcola(String expression, TextView display) throws NumberFormatException{
        Double temp = 0.0;
        String result = "";
        String[] tmp;
	        if (control(expression) == true) {
	               if (expression.contains("√")) {
	                      expression = expression.replace("√", "sqrt");
	               }
	               org.nfunk.jep.JEP parser = new org.nfunk.jep.JEP();
	               parser.addStandardFunctions();
	               parser.addVariable("x", 0);
	               parser.parseExpression(expression);
	               temp = parser.getValue();
	               result = temp.toString();
	          tmp = result.split("\\.");
	          Double n2 = Double.parseDouble(tmp[1]);
	          if (Double.valueOf(n2) == 0){
	               result = (tmp[0]);
	               }
	               if (result.length()>13){
	                      display.setText(result.substring(0, 13));
	               }else{
	                      display.setText(result);
	               }
	        }
	}
	
	public static boolean control(String test){
		if (!test.endsWith(".") && !test.endsWith("+") && !test.endsWith("-")
				&& !test.endsWith("*") && !test.endsWith("/") && !test.endsWith("^") && !test.equals("") && !test.endsWith("√(")){
			return true;
		}else{
			return false;
		}
	}

}
